﻿using BCL.BaseLib.Basics;
using BCL.Tool.Extend;
using DevicesView.Entity;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

namespace DevicesView.Logic.App
{
    [Serializable]
    public class AppResource : IResource
    {
        /// <summary>
        /// 配置文件地址
        /// </summary>
        private static string ConfigPath { get; set; }
        /// <summary>
        /// 服务器配置地址
        /// </summary>
        private static string NetConfigPath { get; set; }



        public static AppResource CurrentResource
        {
            get
            {
                return (AppResource)BCLApplication.Resource;
            }
        }
        public AppResource()
        {
            
        }

        public static AppResource LoadResource()
        {
            AppResource appResource;
            if (File.Exists(ConfigPath))
                appResource = Tool.GetObjectByXML<AppResource>(ConfigPath);
            else
                appResource = new AppResource();

            if (File.Exists(NetConfigPath))
                appResource.NetConfig = Tool.GetObjectByXML<AppNetConfig>(NetConfigPath);
            else
                Tool.ObjectSaveToXML(appResource.NetConfig = AppNetConfig.CreateNetConfig(), NetConfigPath);

            return appResource;
        }

        [Newtonsoft.Json.JsonIgnore]
        [XmlIgnore]
        public string AppCode { get { return Setup.Logic.AppCode; } }

        public SystemUserInfo LoginUser { get; set; }
        
        static AppResource()
        {
            ConfigPath = AppDomain.CurrentDomain.BaseDirectory + "Config\\Resource.xml";
            NetConfigPath = AppDomain.CurrentDomain.BaseDirectory + "Config\\Net.xml";

            if (!Directory.Exists(Path.GetDirectoryName(ConfigPath)))
                Directory.CreateDirectory(Path.GetDirectoryName(ConfigPath));
        }


        public void Save()
        {
            Tool.ObjectSaveToXML(this, ConfigPath);
        }

        [Newtonsoft.Json.JsonIgnore]
        [XmlIgnore]
        public AppNetConfig NetConfig { get; set; }


        public static string LogicServerAddress { get => CurrentResource.NetConfig.Servers.FirstOrDefault(o=>o.ServerName== "LogicServiceAddress")?.Address; }

        public static string OssServerAddress { get => CurrentResource.NetConfig.Servers.FirstOrDefault(o => o.ServerName == "OSSServer")?.Address; }
    }
}
